import {Component} from '@angular/core';
import {App, IonicPage, NavController, NavParams} from 'ionic-angular';
import {QRScanner, QRScannerStatus} from "@ionic-native/qr-scanner";
import {PublicService} from "../../common/public.service";
import {CARD_RECORD_URL, FILL_VOLUME_START_URL} from "../../providers/Constants";
import {HttpService} from "../../providers/HttpService";
import {NativeAudio} from "@ionic-native/native-audio";
import {Vibration} from "@ionic-native/vibration";

/**
 * 连续扫码
 */

@IonicPage()
@Component({
  selector: 'page-con-scanner',
  templateUrl: 'con-scanner.html',
})
export class ConScannerPage {
  light: boolean;//判断闪光灯
  frontCamera: boolean;//判断摄像头
  isShow: boolean = false;//控制显示背景，避免切换页面卡顿
  type: string;

  constructor(private navCtrl: NavController,
              private navParams: NavParams,
              public pub: PublicService,
              public app: App,
              private http: HttpService,
              private vibration: Vibration,
              private nativeAudio: NativeAudio,
              private qrScanner: QRScanner) {
    //默认为false
    this.light = false;
    this.frontCamera = false;
    this.type = this.navParams.get("type");
  }

  ionViewDidLoad() {
    this.scanning();
    //加载音频文件
    this.nativeAudio.preloadSimple("conScanAudioId", "assets/audio/1.mp3");
    this.nativeAudio.preloadSimple("conScanAudioSucId", "assets/audio/success.mp3");
    this.nativeAudio.preloadSimple("conScanAudioErrId", "assets/audio/fail.mp3");
  }

  /**
   * 打卡成功提示音
   */
  sucSound() {
    this.vibration.vibrate(1500);//震动持续时间
    this.nativeAudio.play('conScanAudioSucId').then(() => {
      this.scanning();
    });
  }

  /**
   * 异常情况提示
   */
  errSound() {
    this.vibration.vibrate(1500);//震动持续时间
    this.nativeAudio.play('conScanAudioErrId').then(() => {
      this.scanning();
    });
  }

  /**
   * 扫码
   */
  scanning() {
    this.qrScanner.prepare()
      .then((status: QRScannerStatus) => {
        if (status.authorized) {
          let scanSub = this.qrScanner.scan().subscribe((text: string) => {
            if (text) {
              this.nativeAudio.play('conScanAudioId');
              this.submitWork(text, this.type);
            }
            this.qrScanner.hide(); // hide camera preview
            scanSub.unsubscribe(); // stop scanning
            //this.navCtrl.pop();
          });
          this.qrScanner.show();
        } else if (status.denied) {
        } else {
        }
      })
      .catch((e: any) => console.log('Error is', e));
  }


  /**
   * 提交考勤
   * 如果设置过默认值，则直接提交数据，否则不提交数据
   * @param userCode
   */
  submitWork(userCode: string, cardType: string) {
    let params = {
      sessionId: sessionStorage.getItem("session"),
      groupId: localStorage.getItem("groupId"),
      persionNum: userCode,
      cardType: cardType
    };
    this.http.get(SERVER_URL + CARD_RECORD_URL, '&', params, false).then(res => {
      if (res.success) {
        this.pub.presentLoadingToast(res.msg);
        //默认是设置的默认值
        if (cardType == 'start' && (sessionStorage.getItem("defaultHandleType") || sessionStorage.getItem("defaultAttendanceType")
          || sessionStorage.getItem("defaultProductSeries") || sessionStorage.getItem("defaultProduct"))) {
          this.submitVolume(JSON.stringify([{
            id: "",
            fdUserId: res.data.persionId,
            fdStationId: sessionStorage.getItem("defaultHandleType") ? sessionStorage.getItem("defaultHandleType") : "",
            fdKqType: sessionStorage.getItem("defaultAttendanceType") ? sessionStorage.getItem("defaultAttendanceType") : "",
            fdSeriesId: sessionStorage.getItem("defaultProductSeries") ? sessionStorage.getItem("defaultProductSeries") : "",
            fdProductId: sessionStorage.getItem("defaultProduct") ? sessionStorage.getItem("defaultProduct") : "",
            isSource: 0//是否是源（非增行项）0：是，1：否
          }]));
        }
        setTimeout(() => {
          this.sucSound();
        }, 500);
      } else {
        setTimeout(() => {
          this.errSound();
        }, 500);
        this.pub.presentLoadingToast(res.msg);
        if (res.timeout) {
          setTimeout(() => {
            this.app.getRootNav().setRoot('LoginPage');
          }, 1500);
        }
      }
    });
  }


  /**
   * 提交产量数据
   * 获取页面上所有表单数据
   */
  submitVolume(subDataList: string) {
    let params = {
      sessionId: sessionStorage.getItem("session"),
      groupId: localStorage.getItem("groupId"),
      jsonList: subDataList
    };
    this.http.post(SERVER_URL + FILL_VOLUME_START_URL, '&', params, false).then(res => {
      if (res.success) {
        this.pub.presentLoadingToast("提交成功");
      } else {
        this.pub.presentLoadingToast(res.msg);
        if (res.timeout) {
          setTimeout(() => {
            this.app.getRootNav().setRoot('LoginPage');
          }, 1500);
        }
      }
    });
  }


  ionViewDidEnter() {
    this.showCamera();//页面可见时才执行
    this.isShow = true;//显示背景
  }


  /**
   * 闪光灯控制，默认关闭
   */
  toggleLight() {
    if (this.light) {
      this.qrScanner.disableLight();
    } else {
      this.qrScanner.enableLight();
    }
    this.light = !this.light;
  }

  /**
   * 前后摄像头互换
   */
  toggleCamera() {
    if (this.frontCamera) {
      this.qrScanner.useBackCamera();
    } else {
      this.qrScanner.useFrontCamera();
    }
    this.frontCamera = !this.frontCamera;
  }

  showCamera() {
    (window.document.querySelector('ion-app') as HTMLElement).classList.add('cameraView');
  }

  hideCamera() {
    (window.document.querySelector('ion-app') as HTMLElement).classList.remove('cameraView');
    this.qrScanner.hide();//需要关闭扫描，否则相机一直开着
  }

  ionViewWillLeave() {
    this.hideCamera();
  }

}
